package com.gutsyzhan.edoctor.tools;

import com.gutsyzhan.edoctor.entity.Appointment;
import com.gutsyzhan.edoctor.service.AppointmentService;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppointmentTools {
    @Autowired
    private AppointmentService appointmentService;

    @Tool(
            name = "预约挂号",
            value = "根据参数，先执行工具方法queryDepartment查询是否可预约，" +
                    "并直接给用户回答是否可预约，并让用户确认所有预约信息，用户确认后再进行预约。" +
            "如果用户没有提供具体的医生姓名，请从向量存储中找到一位医生。")
    public String bookAppointment(Appointment appointment) {
        log.info("预约挂号");
        if(appointment == null){
            return "参数无效，无法预约";
        }
        // 查找数据库中是否包含对应的预约记录
        Appointment appointmentDB = appointmentService.getOne(appointment);
        // 判断预约记录是否存在
        if(appointmentDB == null){
            // 设置id为null，防止大模型出现幻觉
            appointment.setId( null);
            if(appointmentService.save( appointment)){
                return "预约成功,并返回预约详情";
            }else{
                return "预约失败";
            }
        }else{
            return "您在相同的科室和时间已有预约";
        }
    }

    @Tool(
            name = "取消预约挂号",
            value = "根据参数，查询预约是否存在；如果存在则删除预约记录并返回“取消预约成功”，否则返回“取消预约失败”"
    )
    public String cancelAppointment(Appointment appointment) {
        log.info("取消预约挂号");
        if(appointment == null){
            return "参数无效，无法取消预约";
        }
        // 查找数据库中是否包含对应的预约记录
        Appointment appointmentDB = appointmentService.getOne(appointment);
        // 判断预约记录是否存在
        if(appointmentDB != null){
            boolean removed = appointmentService.removeById(appointmentDB.getId());
            if(removed){
                return removed ? "取消预约成功" : "取消预约失败";
            }
        }
        return "您没有预约记录，请核对预约科室、时间等信息";
    }

    @Tool(
            name = "查询是否有号源",
            value = "根据科室名称、日期、时间段和医生名称（可选）查询是否有可预约号源，并返回结果"
    )
    public boolean queryDepartment(@P(value = "科室名称") String departmentName,
                                   @P(value = "日期") String date,
                                   @P(value = "时间，可选值：上午、下午")String time,
                                   @P(value = "医生名称", required = false) String doctorName) {
        log.info("查询是否有号源");
        log.info("科室名称：{}，日期：{}，时间：{}，医生名称：{}", departmentName, date, time, doctorName);
        // TODO: 查询医生排班信息，以下是伪代码逻辑说明

        if (doctorName == null || doctorName.isEmpty()) {
            // 未指定医生，查询该科室、日期、时间是否有可预约医生
            return true;
        } else {
            // 指定了医生
            // 检查医生是否有排班
            boolean hasSchedule = true;
            if (!hasSchedule) {
                return false;
            }
            // 检查排班是否已约满
            boolean isFull = false;
            return !isFull;
        }
    }
}
